<?php
defined('SYS_RUN') or exit();

class Template {

    const DIR_TEMPLATE = 'view/template/';

    const DIR_LAYOUT = 'view/layout/';

    const PATTERN_TEMPLATE = '%s.php';

    const PATTERN_LAYOUT = '%s.php';

    const DEFAULT_LAYOUT = 'base';

    private $title;

    public function setTitle($title) {
        $this->title = $title;
    }

    public function getTitle($isHtml = true) {
        if($isHtml)
            return '<title>'.$this->title.'</title>';
        else $this->title;
    }

    public function render($template, $params = null, $layout = null) {
        $templateHtml = $this->_fetch($this->_getTemplateFile($template), $params);

        $this->_display($this->_getLayoutFile($layout), array(
            'head'  => $this->_getHeader(),
            'body'  => $templateHtml
        ));
    }

    public function renderPartial($template, $params = null, $returnHtml = false) {
        if($returnHtml)
            return $this->_fetch($this->_getTemplateFile($template), $params);
        else {
            $this->_display($this->_getTemplateFile($template), $params);
            return true;
        }
    }

    private function _getHeader() {
        $html = $this->getTitle();
            foreach(Lib::get('script')->getCachedFilesHtml() as $file) {
                $html .= $file;
            }
        return $html;
    }

    private function _getLayoutFile($layout) {
        $layoutFile = DIR_APPLICATION.self::DIR_LAYOUT;
        if($layout)
            $layoutFile .= sprintf(self::PATTERN_TEMPLATE, $layout);
        else
            $layoutFile .= self::DEFAULT_LAYOUT.'.php';
        if(!file_exists($layoutFile))
            Error::trigger('Layout file not found:'. $layoutFile);
        return $layoutFile;
    }

    private function _getTemplateFile($template) {
        $templateFile = DIR_APPLICATION.self::DIR_TEMPLATE.sprintf(self::PATTERN_TEMPLATE, $template);
        if(!file_exists($templateFile))
            Error::trigger('Template file not found:'. $templateFile);
        return $templateFile;
    }

    private function _display($file, $params = null) {
        if($params) extract($params);
        include $file;
    }

    private function _fetch($file, $params = null) {
        ob_start();
        $this->_display($file, $params);
        $content = ob_get_contents();
        ob_end_clean();
        return $content;
    }
}